package com.kevin.Code.OfferReviewVersion1;

/**
 * @author Vinlee Xiao
 * @Classname OfferI_57
 * @Description Leetcode 34 同 剑指Offer 57 二刷 增加解法
 * @Date 2022/1/20 21:52
 * @Version 1.0
 */
public class OfferI_57 {
    public int[] searchRange(int[] nums, int target) {
        //在二分查找找出第一个大于等于target的坐标
        //得到第一个等于target的坐标
        int leftIndex = binarySearch(nums, target, true) + 1;
        int rightIndex = binarySearch(nums, target, false) - 1;
        //用于边界判断
        if (leftIndex > nums.length - 1 || nums[leftIndex] != target) {
            leftIndex = -1;
        }

        if (rightIndex < 0 || nums[rightIndex] != target) {
            rightIndex = -1;
        }

        return new int[]{leftIndex, rightIndex};
    }

    /**
     *
     */
    private int binarySearch(int[] nums, int target, boolean flag) {

        int left = 0;
        int right = nums.length - 1;
        int ans = 0;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target || (flag && nums[mid] >= target)) {
                right = mid - 1;

            } else {
                left = mid + 1;
            }
        }
        return flag == true ? right : left;
    }
}
